<template>
  <div class="comp-detail-table">
    <div class="table-container" :style="{ height: `${height - 216}px` }">
      <div class="project-info">
        <div class="tag">项目基本信息</div>
        <div class="info-content">
          <a-form-model
            :model="form"
            :rules="rules"
            :label-col="{ span: 1 }"
            :wrapper-col="{ span: 30 }"
          >
            <a-form-model-item prop="projectName">
              <span>项目名称：</span>
              <span class="ant-form-text">
                <a-input
                  v-if="!lock && userRole < 3"
                  v-model="form.projectName"
                  placeholder="请输入"
                />
                <span v-else class="ant-form-text">{{ form.projectName }}</span>
              </span>
              <span class="ant-form-text"
                >上次更新时间： {{ form.gmtModify }}</span
              >
              <span class="ant-form-text">创建时间： {{ form.gmtCreate }}</span>
              <!-- <span class="ant-form-text">{{ form.projectName }}</span> -->
            </a-form-model-item>
            <a-form-model-item>
              <span>项目描述：</span>
              <a-textarea
                v-if="!lock && userRole < 3"
                v-model="form.description"
                :style="{ width: '513px' }"
                placeholder="请输入"
                style="height: 68px; resize: none;"
              />
              <span v-else class="ant-form-text">{{ form.description }}</span>
            </a-form-model-item>
          </a-form-model>
        </div>
        <div v-if="userRole < 3 && lock === false" class="footer-content">
          <a-button class="ok-btn" @click="changeProjectInfo">确定 </a-button>
          <router-link to="/management">
            <a-button class="cancel-btn">取消</a-button>
          </router-link>
        </div>
      </div>
      <div class="member-info">
        <div class="tag">成员信息</div>
        <a-table
          class="member-table"
          :columns="userRole < 3 ? columns : columns.slice(0, 3)"
          :data-source="data"
          :pagination="paginationConfig"
        >
          <!-- <div v-if="record.role!=='管理员'" slot="actions" slot-scope="_, record">
            <a-button v-if="record.key!==modifiedId" type="link" style="width: 88px;" class="action-button" @click="() => setModifiedId(record.key, record.role)">修改成员角色</a-button>
            <a-button v-else type="link" style="width: 29px;" class="action-button" @click="updateRole">确定</a-button>
            <a-divider type="vertical" />
            <a-button v-if="record.key!==modifiedId" type="link" style="width: 29px;" class="action-button" @click="() => setDeleteVisible(record.key)">删除</a-button>
            <a-button v-else type="link" style="width: 29px;" class="action-button" @click="cancelRole">取消</a-button>
          </div> -->
          <div slot="name" slot-scope="text, record">
            <span v-if="record.addedItem">
              <a-select
                placeholder="请搜索"
                show-search
                size="small"
                class="select"
                @search="handleSearch"
                @change="(value) => changeMemberName(record.key, value)"
              >
                <a-icon
                  slot="suffixIcon"
                  type="search"
                  :style="{ 'font-size': '18px', margin: '-3px -4px' }"
                />
                <a-select-option
                  v-for="option in userList"
                  :key="option.id"
                  :value="option.name"
                >
                  {{ option.name }}
                </a-select-option>
              </a-select>
            </span>
            <span v-else>{{ text }}</span>
          </div>
          <div slot="roleName" slot-scope="text, record">
            <span v-if="record.editable || record.addedItem">
              <a-select
                size="small"
                :style="{
                  width: '140px',
                  border: '2px solid rgba(105, 115, 255, 0.25)',
                  borderRadius: '4px',
                }"
                :default-value="text"
                @change="(e) => changeMemberRole(e, record.key)"
              >
                <a-select-option
                  v-for="role in roleList"
                  :key="role.id"
                  :value="role.name"
                >
                  {{ role.name }}
                </a-select-option>
              </a-select>
            </span>
            <span v-else>{{ text }}</span>
          </div>
          <div slot="action" slot-scope="text, record">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">保存</a>
              <a-divider type="vertical" />
              <a @click="() => cancel(record.key)">取消</a>
            </span>
            <span v-if="record.addedItem">
              <a @click="() => cancelAdd(record.key)">取消</a>
              <a-divider type="vertical" />
              <a @click="() => saveAdd(record.key)">确定</a>
            </span>
            <span
              v-if="
                !record.editable &&
                !record.addedItem &&
                userRole < record.roleId
              "
            >
              <a
                :disabled="lock || editingKey !== ''"
                @click="() => edit(record.key)"
                >修改</a
              >
              <span v-if="userRole < record.roleId">
                <a-divider type="vertical" />
                <a
                  :disabled="lock || editingKey !== ''"
                  @click="() => setDeleteVisible(record.key, record.userId)"
                  >删除</a
                >
              </span>
            </span>
          </div>
        </a-table>
        <a-button
          v-if="userRole < 3"
          type="primary"
          :disabled="lock || editingKey !== ''"
          class="add-button"
          @click="addMember"
          >添加成员
        </a-button>
        <!-- <a-button v-if="userRole === '管理者'" type="primary" class="add-button" @click="setAddMemberVisible">添加成员</a-button> -->
      </div>
      <div v-if="userRole < 3" class="advanced-info">
        <div class="tag">高级信息</div>
        <div class="modify-status">
          <span class="modify-text">项目不可修改</span>
          <a-switch v-model="lock" @change="onStatusChange" />
        </div>
      </div>
    </div>

    <a-modal
      :visible="deleteVisible"
      ok-text="确定"
      cancel-text="取消"
      centered
      @ok.stop="deleteMember"
      @cancel.stop="cancelDelete"
    >
      <p>
        <a-icon
          type="question-circle"
          theme="filled"
          :style="{ color: 'orange', margin: '0 10px 0 0' }"
        />
        确定删除该成员吗？
      </p>
      <p v-if="deleteDataStatus">
        当前用户在本项目中贡献的数据已被其他用户使用，请确认是否需要继续删除
      </p>
      <p v-else>删除后，项目内该成员对应的数据将被清空</p>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import ProjectStore from '@/store/modules/project'
import UserStore from '@/store/modules/user'
import moment from 'moment'
import { debounce } from 'lodash'
import { queryInfoByName } from '@/api/user'
import { userDatasetUsedCheck } from '@/api/home'

@Component({})
export default class DetailsTable extends Vue {
  @Prop() projectId!: number

  public height = document.body.clientHeight
  private lock: boolean = false
  private userRole: any = null
  private columns = [
    {
      title: '成员',
      dataIndex: 'name',
      key: 'name',
      scopedSlots: { customRender: 'name' },
      width: '25%',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      scopedSlots: { customRender: 'roleName' },
      width: '25%',
    },
    {
      title: '授予时间',
      dataIndex: 'gmtModify',
      key: 'gmtModify',
      scopedSlots: { customRender: 'gmtModify' },
      width: '25%',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      scopedSlots: { customRender: 'action' },
      width: '25%',
    },
  ]

  private projectInfoVisible: boolean = false
  private form = {
    projectName: '',
    description: '',
    gmtModify: '',
    gmtCreate: '',
  }
  private rules = {
    projectName: [{ message: '请输入项目名', trigger: 'blur' }],
  }

  // 分页设置
  private paginationConfig: any = { pageSize: 10 }

  // 删除成员
  private deleteVisible: boolean = false
  private deletedId: number | null = null
  // 删除成员的数据是否被其他用户使用
  private deleteDataStatus: boolean = false

  // 修改权限
  private modifiedKey: number | null = null
  private modifiedId: number | null = null
  private modifiedRole: string | null = null

  public data = this.projectAuths.map((item) => ({ ...item }))
  public cacheData = this.projectAuths.map((item) => ({ ...item }))
  public editingKey: any = ''

  // 记录表单输入内容防止丢失
  public formInputName: string = ''
  public formInputDescription: string = ''

  public async created(): Promise<void> {
    this.height = document.body.clientHeight
    this.data = []
    this.lock = ProjectStore.projectStatus === 1
    window.addEventListener('resize', this.handleResize)

    this.getProjectInfo()

    await ProjectStore.queryProjectAuth(this.projectId)
    await ProjectStore.getRoleList()
    this.data = this.projectAuths.map((item) => ({ ...item }))
    this.cacheData = this.projectAuths.map((item) => ({ ...item }))
    const userId = UserStore.currentUser ? UserStore.currentUser.id : null
    const user = this.data.filter((item) => userId === item.userId)
    this.userRole = user.length === 0 ? 1 : user[0].roleId
  }

  // 弃用20210428
  /* 查看项目信息 */
  // public async setProjectInfoVisible() {
  //   console.log(this.form)
  // }
  // 获取项目信息
  public async getProjectInfo() {
    const response = await ProjectStore.queryProjectById(String(this.projectId))
    this.form.projectName = response.name
    if (this.formInputName) {
      this.form.projectName = this.formInputName
    }
    this.form.description = response.description
    if (this.formInputDescription) {
      this.form.description = this.formInputDescription
    }
    this.form.gmtModify = moment(response.gmtModify).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    this.form.gmtCreate = moment(response.gmtCreate).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    this.lock = response.lock === 1

    // 初始化表格信息备份
    this.formInputDescription = ''
    this.formInputName = ''
  }

  // 修改项目信息
  public async changeProjectInfo() {
    this.formInputName = this.form.projectName
    this.formInputDescription = this.form.description
    await ProjectStore.updateProjectInfoById({
      description: this.form.description,
      id: this.projectId,
      name: this.form.projectName,
    })
    this.getProjectInfo()
  }

  // 高级信息 项目是否可修改
  public async onStatusChange(value: any) {
    console.log(value)
    const lockStatus = value ? 1 : 0
    await ProjectStore.changeProjectStatus({
      id: this.projectId,
      lock: lockStatus,
    })
    if (lockStatus && this.editingKey !== '') {
      if (this.editingKey === '-1') {
        this.cancelAdd()
      } else {
        this.cancel(this.editingKey)
      }
    }
    this.getProjectInfo()
  }

  public handleResize() {
    this.height = document.body.clientHeight
  }

  // 获取当前项目成员信息
  public get projectAuths(): Array<any> {
    if (!ProjectStore.projectAuth) {
      return []
    }
    return ProjectStore.projectAuth.map((auth) => {
      return {
        key: auth.id,
        userId: auth.userId,
        name: auth.userName,
        gmtModify: moment(auth.gmtModify).format('YYYY-MM-DD HH:mm:ss'),
        roleName: auth.roleName,
        roleId: auth.roleId,
        read: true,
        edit: auth.roleId !== 1,
        editable: false,
        addedItem: false,
      }
    })
  }

  public get roleList(): Array<any> {
    if (!ProjectStore.roleList) {
      return []
    }
    return ProjectStore.roleList
  }

  // 弃用20210428
  /* 修改权限 */

  // public setModifiedId(id: number, role: string): void {
  //   this.modifiedId = id
  //   this.modifiedRole = role
  // }

  // public changeRole(value: string): void {
  //   this.modifiedRole = value
  // }

  // public cancelRole(): void {
  //   this.modifiedId = null
  //   this.modifiedRole = null
  // }

  // public async updateRole(): Promise<void> {
  //   if(this.modifiedId!==null && this.modifiedRole!==null){
  //     const authNumber= this.modifiedRole==='游客'?1:(this.modifiedRole==='协作者'?2:3)
  //     await ProjectStore.updateAuth({auth:authNumber,id:this.modifiedId})
  //     this.modifiedId = null
  //     this.modifiedRole = null
  //   }
  // }

  /* 删除成员 */
  public setDeleteVisible(id: any, userId: any): void {
    userDatasetUsedCheck({
      data: {
        projectId: this.projectId,
        userId,
      },
    }).then((result) => {
      this.deleteVisible = true
      this.deletedId = id
      this.deleteDataStatus = result.data.result.otherUsersAreUsing
    })
  }

  public cancelDelete(): void {
    this.deleteVisible = false
  }

  public async deleteMember(): Promise<void> {
    await ProjectStore.deleteAuth({
      id: this.deletedId,
      projectId: this.projectId,
    })
    this.deleteVisible = false
    this.data = this.projectAuths.map((item) => ({ ...item }))
    this.cacheData = this.projectAuths.map((item) => ({ ...item }))
  }

  public setAddMemberVisible(): void {
    ProjectStore.setAddMemberModalVisible(true)
  }

  // 添加成员
  public addMember(): void {
    this.paginationConfig = { pageSize: 10, current: 1 }
    this.data.unshift({
      key: this.data.length,
      userId: 23333,
      name: ' ',
      gmtModify: '',
      roleName: '项目开发者',
      roleId: 3,
      read: true,
      edit: 1,
      editable: false,
      addedItem: true,
    })
    this.editingKey = '-1'
  }

  // 所有可以选择的成员名单
  private allMembers: Array<any> = []

  // 从所有可选的成员名单中过滤已添加的成员和自己   < 弃用  hou jinhui 20210118>
  public get memberOptions(): Array<any> {
    const addedNames: Set<string> = new Set()
    ProjectStore.projectAuth.forEach((m) => {
      addedNames.add(m.userName)
    })
    // 去掉自己
    addedNames.add(UserStore.currentUser ? UserStore.currentUser.name : '')
    return this.allMembers.filter((m) => !addedNames.has(m.name))
  }

  // ------ replace ----
  // 模糊搜索 用户
  public userList: any[] = []

  // 关键字 模糊搜索用户
  public handleSearch(searchKey: string) {
    if (searchKey.trim().length >= 2) {
      this.queryUsersByName(searchKey.trim())
    }
  }

  // 防抖
  private queryUsersByName = debounce(
    (searchKey: string) => this._handleSearch(searchKey),
    100
  )

  public _handleSearch(searchKey: string) {
    const parameters = {
      name: searchKey,
    }
    queryInfoByName({ data: parameters })?.then((response: any) => {
      if (response.data.code === 100) {
        // 去掉自己
        const filterUsers = response.data.result.filter(
          (user: any) => user.id !== UserStore.currentUser?.id
        )
        this.userList = filterUsers
        this.allMembers = filterUsers // 保持原代码 （changeMemberName 中 根据 name 查 id）
      }
    })
  }

  public changeMemberName(key: any, name: string) {
    const newData = [...this.data]
    const newCacheData = [...this.cacheData]
    const i = this.allMembers.map((p) => p.name).indexOf(name)

    const target = newData.filter((item) => key === item.key)[0]
    console.log(this.allMembers[i])
    if (target) {
      target.id = this.allMembers[i].id
      target.userId = this.allMembers[i].id
      target.name = name
      this.data = newData
      // Object.assign(targetCache, target)
      this.cacheData = newCacheData
    }
  }

  // 确定添加
  public async saveAdd(key: any) {
    console.log('saveAdd')
    const newData = [...this.data]
    const newCacheData = [...this.cacheData]
    const target = newData.filter((item) => key === item.key)[0]
    if (target) {
      target.addedItem = false
      this.data = newData
      // Object.assign(targetCache, target)
      this.cacheData = newCacheData
      await ProjectStore.createNewAuth({
        projectId: this.projectId,
        userRoles: [{ roleId: target.roleId, userId: target.userId }],
      })
      this.data = this.projectAuths.map((item) => ({ ...item }))
      this.cacheData = this.projectAuths.map((item) => ({ ...item }))
      this.getProjectInfo()
    }
    this.editingKey = ''
    this.paginationConfig = { pageSize: 10 }
  }

  // 取消添加
  public cancelAdd() {
    this.editingKey = ''
    this.data = this.projectAuths.map((item) => ({ ...item }))
    this.cacheData = this.projectAuths.map((item) => ({ ...item }))
    this.paginationConfig = { pageSize: 10 }
  }

  // 修改
  public changeMemberRole(value: any, key: any) {
    const newData = [...this.data]
    const target = newData.filter((item) => key === item.key)[0]
    console.log(value)
    if (target) {
      target.roleName = value
      target.roleId =
        value === '项目管理员' ? 2 : value === '项目开发者' ? 3 : 4
      this.data = newData
    }
  }

  public edit(key: any) {
    const newData = [...this.data]
    const target = newData.filter((item) => key === item.key)[0]
    this.editingKey = key
    if (target) {
      target.editable = true
      this.data = newData
      console.log('edit')
    }
  }

  public async save(key: any) {
    const newData = [...this.data]
    const newCacheData = [...this.cacheData]
    const target = newData.filter((item) => key === item.key)[0]
    const targetCache = newCacheData.filter((item) => key === item.key)[0]
    console.log(target, targetCache)
    if (target.roleId === 4) {
      // 修改成项目访客需确认
      this.$confirm({
        title: '确认要更改为项目访客吗？',
        content: '项目访客将失去所有的pipeline',
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          if (target && targetCache) {
            target.editable = false
            await ProjectStore.updateAuth({
              projectId: this.projectId,
              roleId: target.roleId,
              userId: target.userId,
            })
            this.data = this.projectAuths.map((item) => ({ ...item }))
            Object.assign(targetCache, target)
            this.cacheData = newCacheData
            console.log('save')
          }
        },
      })
    } else if (target && targetCache) {
      target.editable = false
      await ProjectStore.updateAuth({
        projectId: this.projectId,
        roleId: target.roleId,
        userId: target.userId,
      })
      this.data = this.projectAuths.map((item) => ({ ...item }))
      Object.assign(targetCache, target)
      this.cacheData = newCacheData
      console.log('save')
    }

    this.editingKey = ''
  }

  public async cancel(key: any) {
    const newData = [...this.data]
    const target = newData.filter((item) => key === item.key)[0]
    this.editingKey = ''

    if (target) {
      Object.assign(
        target,
        this.cacheData.filter((item) => key === item.key)[0]
      )
      target.editable = false
      this.data = newData
      console.log('cancel')
    }
    this.data = this.projectAuths.map((item) => ({ ...item }))
    this.cacheData = this.projectAuths.map((item) => ({ ...item }))
  }
}
</script>

<style lang="less">
@import '@/constants';

.comp-detail-table {
  .ant-form-text {
    margin-right: 190px;
  }

  .table-container {
    font-size: @TEXT_FONT_SIZE;
    margin-top: 12px;
    overflow-y: auto;

    .ant-select {
      margin-left: -8px;
      margin-top: -2px;
    }

    &::-webkit-scrollbar {
      height: 6px;
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(144, 147, 153, 0.5);
      border-radius: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
      border-radius: 5px;
    }
  }

  // .project-info {
  //   height: 100%;
  // }

  /* tag */
  .tag {
    color: #373b52;
    font-size: 16px;
    font-weight: 500;
    height: 22px;
    letter-spacing: 1px;
    line-height: 22px;
    margin-bottom: 24px;
    padding-left: 8px;
    position: relative;
    width: 120px;

    span {
      color: #e74c3c;
      font-size: 14px;
      font-weight: 500;
    }

    &::before {
      background: #6973ff;
      content: '';
      height: 18px;
      left: 0;
      position: absolute;
      top: 2px;
      width: 2px;
    }
  }

  .add-button {
    background: #fff;
    border: 1px solid #6973ff;
    color: #6973ff;
    font-size: 14px;
    font-weight: 400;
    height: 28px;
    letter-spacing: 1px;
    line-height: 20px;
    margin-bottom: 10px;
    margin-top: 15px;
    text-align: center;
    width: 100px;
  }

  .modify-status {
    margin-left: 88px;
    padding-bottom: 20px;
  }

  .modify-text {
    height: 688px;
    padding-right: 4px;
    width: 1408px;
  }

  .info-content {
    align-content: flex-start;
    margin-left: 88px;
    text-align: left;
  }

  .footer-content {
    height: 40px;
    right: 20px;
  }

  .cancel-btn {
    background: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    color: #666;
    float: right;
    font-size: 14px;
    font-weight: 400;
    height: 32px;
    margin-right: 12px;
    width: 65px;
  }

  .ok-btn {
    background: #6973ff;
    border-radius: 4px;
    color: #fff;
    float: right;
    font-size: 14px;
    height: 32px;
    margin-right: 40px;
    width: 65px;
  }

  .project-info {
    background: #fff;
    margin-bottom: 10px;
    padding: 24px 24px 9px;
  }

  .member-info {
    background: #fff;
    margin-bottom: 10px;
    padding: 24px 24px 9px;
  }

  .advanced-info {
    background: #fff;
    padding: 24px 24px 9px;
  }
}
</style>
